import React, { useCallback, useEffect, useState } from "react";

type SQUARE_VALUE = "X" | "O" | null;

type SquareProps = {
  value: SQUARE_VALUE;
  index: number;
  handleParentClick: (index: number) => void;
};

const Square = React.memo((props: SquareProps) => {
  const { value, index, handleParentClick } = props;

  return (
    <div
      className="w-[40px] h-[40px] border-[1px] border-black flex justify-center items-center cursor-pointer"
      onClick={() => handleParentClick(index)}
    >
      {value}
    </div>
  );
});
export default function Home() {
  const [squares, setSquares] = useState(Array(9).fill(null));
  const [nextPlayer, setNextPlayer] = useState<SQUARE_VALUE>("X");
  const [message, setMessage] = useState<string[]>([]);
  const [winner, setWinner] = useState<SQUARE_VALUE | null>(null);

  const handleClick = (i: number) => {
    if (squares[i] || winner) return;
    const newSquares = [...squares];
    newSquares[i] = nextPlayer;
    setSquares(newSquares);
    setNextPlayer(nextPlayer === "X" ? "O" : "X");
    setMessage((msg) => [
      ...msg,
      `${nextPlayer} 落子第${message.length + 1}步`,
    ]);
  };

  const getWinner = useCallback(() => {
    const winnerLines = [
      [0, 1, 2],
      [3, 4, 5],
      [6, 7, 8],
      [0, 3, 6],
      [1, 4, 7],
      [2, 5, 8],
      [0, 4, 8],
      [2, 4, 6],
    ];
    for (const line of winnerLines) {
      const [a, b, c] = line;
      if (
        squares[a] !== null &&
        squares[a] === squares[b] &&
        squares[a] === squares[c]
      ) {
        return squares[a];
      }
    }
    return null;
  }, [squares]);
  useEffect(() => {
    const win = getWinner();
    if (win) {
      setWinner(win);
    }
  }, [squares, getWinner]);

  return (
    <div className="flex justify-between w-72 mx-auto">
      <div className="flex flex-wrap w-[120px] h-[120px]">
        {Array.from({ length: 9 }).map((_, i) => {
          return (
            <Square
              key={i}
              value={squares[i]}
              index={i}
              handleParentClick={() => handleClick(i)}
            />
          );
        })}
      </div>
      <div className="flex flex-col justify-center items-center">
        {winner ? (
          <h1>{`胜利者是${winner}`}</h1>
        ) : (
          <h1>{`下一步是${nextPlayer}`}</h1>
        )}
        {message.map((item, index) => {
          return <p key={index}>{item}</p>;
        })}
      </div>
    </div>
  );
}
